{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍数据分析可视化</title>
    <script src="{% static 'js/echarts.min.js' %}"></script>
    <script src="{% static 'js/echarts-wordcloud.min.js' %}"></script>
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

    <style>
        body { padding: 20px; }
        .chart-container { margin-bottom: 30px; }
        .card { margin-bottom: 20px; }
        .btn-filter { margin-top: 20px; }
        .author-selector { margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center mb-4">书籍数据分析可视化</h1>

        <!-- 作者选择器 -->
        <div class="card bg-light p-4 author-selector">
            <h3 class="mb-3">选择作者查看书籍</h3>
            <div class="row">
                <div class="col-md-6">
                    <select class="form-select" id="authorSelector">
                        <option value="">-- 选择作者 --</option>
                        {% for author in top_authors %}
                            <option value="{{ author }}">{{ author }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-6">
                    <button class="btn btn-primary" onclick="loadBooksByAuthor()">查看书籍</button>
                </div>
            </div>
        </div>

        <!-- 作者书籍列表 -->
        <div class="row chart-container">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">作者书籍列表</div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>书名</th>
                                    <th>价格</th>
                                    <th>推荐数</th>
                                    <th>收藏数</th>
                                    <th>出版社</th>
                                    <th>标签</th>
                                </tr>
                            </thead>
                            <tbody id="authorBooksTable"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row chart-container">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">TOP10作者书籍占比</div>
                    <div class="card-body">
                        <div id="authorPieChart" style="width: 100%; height: 400px;"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">TOP10出版社书籍数量</div>
                    <div class="card-body">
                        <div id="publisherLineChart" style="width: 100%; height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row chart-container">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">书籍标签云</div>
                    <div class="card-body">
                        <div id="tagCloudChart" style="width: 100%; height: 400px;"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">收藏数与推荐数关系</div>
                    <div class="card-body">
                        <div id="favCommendScatterChart" style="width: 100%; height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row chart-container">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">价格分布</div>
                    <div class="card-body">
                        <div id="priceBarChart" style="width: 100%; height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>


    </div>

    <script>
        // 从Django模板获取数据
        const chartData = JSON.parse('{{ chart_data|escapejs }}');

        // 初始化图表实例
        const authorPieChart = echarts.init(document.getElementById('authorPieChart'));
        const publisherLineChart = echarts.init(document.getElementById('publisherLineChart'));
        const tagCloudChart = echarts.init(document.getElementById('tagCloudChart'));
        const favCommendScatterChart = echarts.init(document.getElementById('favCommendScatterChart'));
        const priceBarChart = echarts.init(document.getElementById('priceBarChart'));

        // 渲染所有图表
        function renderCharts() {
            console.log('标签云数据:', chartData.tag_cloud);
            // 1. TOP10作者饼图
            renderAuthorPieChart(chartData.author_pie);
            // 2. TOP10出版社折线图
            renderPublisherLineChart(chartData.publisher_line);
            // 3. 标签云图
            renderTagCloudChart(chartData.tag_cloud);
            // 4. 收藏数与推荐数关系图
            renderFavCommendScatterChart(chartData.fav_commend);
            // 5. 价格分布柱状图
            renderPriceBarChart(chartData.price_bar);
        }

        // 渲染TOP10作者饼图
        function renderAuthorPieChart(data) {
            authorPieChart.setOption({
                title: { text: 'TOP10 作者书籍占比' },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'horizontal',
                    left: 'center',
                    bottom: '5%',
                    padding: [10, 0],
                    itemGap: 15,
                    data: data.map(item => item.author)
                },
                series: [{
                    name: '书籍数量',
                    type: 'pie',
                    radius: '50%',
                    data: data.map(item => ({
                        name: item.author,
                        value: item.count
                    })),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            });
        }

        // 渲染TOP10出版社折线图
        function renderPublisherLineChart(data) {
            publisherLineChart.setOption({
                title: { text: 'TOP10 出版社书籍数量' },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: data.map(item => item.publisher),
                    axisLabel: {
                        rotate: 45,
                        interval: 0
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '书籍数量'
                },
                series: [{
                    name: '书籍数量',
                    type: 'line',
                    smooth: true,
                    data: data.map(item => item.count),
                    areaStyle: {},
                    lineStyle: {
                        width: 3
                    },
                    itemStyle: {
                        color: '#2ecc71'
                    }
                }]
            });
        }

        // 渲染标签云图
        function renderTagCloudChart(data) {
            if (!data || data.length === 0) {
                tagCloudChart.setOption({
                    title: {
                        text: '书籍标签云 (无数据)',
                        left: 'center',
                        top: 'center'
                    },
                    series: []
                });
                return;
            }

            tagCloudChart.setOption({
                title: {
                    text: '书籍标签云',
                    left: 'center'
                },
                tooltip: {
                    show: true,
                    formatter: function(params) {
                        return params.name + ': ' + params.value;
                    }
                },
                series: [{
                    type: 'wordCloud',
                    shape: 'circle',
                    sizeRange: [12, 60],
                    rotationRange: [-90, 90],
                    rotationStep: 45,
                    gridSize: 8,
                    drawOutOfBound: false,
                    textStyle: {
                        fontFamily: 'sans-serif',
                        fontWeight: 'bold',
                        color: function () {
                            return 'rgb(' + [
                                Math.round(Math.random() * 160),
                                Math.round(Math.random() * 160),
                                Math.round(Math.random() * 160)
                            ].join(',') + ')';
                        }
                    },
                    emphasis: {
                        focus: 'self',
                        textStyle: {
                            shadowBlur: 10,
                            shadowColor: '#333'
                        }
                    },
                    data: data
                }]
            });
        }

        // 渲染收藏数与推荐数关系图
        function renderFavCommendScatterChart(data) {
            const points = data.map(item => [
                item.fav_count || 0, // 处理空值
                item.commend_count || 0
            ]);

            // 计算最大推荐数用于可视化映射
            const maxCommend = Math.max(...points.map(p => p[1]), 1);

            favCommendScatterChart.setOption({
                title: { text: '收藏数与推荐数关系' },
                tooltip: {
                    formatter: function(params) {
                        const xValue = params.data[0]; // 收藏数（x轴值）
                        const yValue = params.data[1]; // 推荐数（y轴值）
                        return `收藏数: ${xValue}<br>推荐数: ${yValue}`;
                    }
                },
                xAxis: {
                    type: 'value',
                    name: '收藏数',
                    nameLocation: 'end',
                    nameGap: 15
                },
                yAxis: {
                    type: 'value',
                    name: '推荐数',
                    nameLocation: 'end',
                    nameGap: 15
                },
                visualMap: {
                    min: 0,
                    max: maxCommend,
                    dimension: 1,
                    orient: 'vertical',
                    right: 10,
                    top: 'center',
                    text: ['高', '低'],
                    calculable: true
                },
                series: [{
                    type: 'scatter',
                    symbolSize: function (val) {
                        // 根据推荐数调整点大小
                        return Math.sqrt(val[1] + 1) * 3;
                    },
                    data: points,
                    itemStyle: {
                        color: '#9b59b6'
                    }
                }]
            });
        }

        // 渲染价格分布柱状图
        function renderPriceBarChart(data) {
            priceBarChart.setOption({
                title: { text: '价格分布' },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: data.labels,
                    axisLabel: {
                        interval: 0,
                        rotate: 30
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '书籍数量'
                },
                series: [{
                    name: '书籍数量',
                    type: 'bar',
                    data: data.data,
                    itemStyle: {
                        color: function(params) {
                            const colorList = [
                                '#e74c3c', // 负值 - 红色
                                '#3498db', '#2980b9', '#1f618d', '#154360', '#2c3e50', '#7f8c8d' // 其他区间
                            ];
                            return colorList[params.dataIndex];
                        }
                    },
                    label: {
                        show: true,
                        position: 'top'
                    }
                }]
            });
        }

        // 根据作者加载书籍
        function loadBooksByAuthor() {
            const author = document.getElementById('authorSelector').value;
            if (!author) {
                alert('请选择作者');
                return;
            }

            fetch(`/visualization/books_by_author/?author=${encodeURIComponent(author)}`)
                .then(response => response.json())
                .then(data => renderAuthorBooksTable(data.books))
                .catch(error => console.error('加载书籍失败:', error));
        }

        // 渲染作者书籍表格
        function renderAuthorBooksTable(books) {
            const tableBody = document.getElementById('authorBooksTable');
            tableBody.innerHTML = '';

            if (books.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="5" class="text-center">该作者暂无书籍数据</td></tr>';
                return;
            }
            books.forEach(book => {
                const row = document.createElement('tr');
                row.innerHTML = `

                    <td><a href="${book.url}">${book.title || '无数据'}</a></td>
                    <td>${book.price !== undefined ? book.price : '无数据'}</td>
                    <td>${book.commend_count !== undefined ? book.commend_count : '无数据'}</td>
                    <td>${book.fav_count !== undefined ? book.fav_count : '无数据'}</td>
                    <td>${book.publisher || '无数据'}</td>
                    <td>${book.tags || '无数据'}</td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 页面加载完成后渲染图表
        document.addEventListener('DOMContentLoaded', renderCharts);
    </script>

</body>
</html>